/*
 *    Copyright 2008-2009 Simone Tripodi
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.testnguice.providers.xml;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.digester.Rule;

/**
 * Digester rule that sets the the test methods arguments.
 *
 * @author Simone Tripodi
 * @version $Id: ObjectArraySetArgumentRule.java 144 2009-11-24 07:48:25Z simone.tripodi $
 */
final class ObjectArraySetArgumentRule extends Rule {

    /**
     * The test method arguments types.
     */
    private final Class<?>[] types;

    /**
     * The test method arguments converters.
     */
    private final Converter[] typeConverters;

    /**
     * The current test method argument index.
     */
    private int argumentIndex = 0;

    /**
     * Instantiates a new test methods arguments setter.
     *
     * @param types the test method arguments types.
     */
    public ObjectArraySetArgumentRule(final Class<?>[] types) {
        this.types = types;
        this.typeConverters = new Converter[types.length];
        for (int i = 0; i < types.length; i++) {
            this.typeConverters[i] = ConvertUtils.lookup(types[i]);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void body(final String namespace, final String name, final String text) throws Exception {
        if (this.argumentIndex < this.types.length) {
            Object[] arguments = (Object[]) this.digester.peek();
            arguments[this.argumentIndex] = this.typeConverters[this.argumentIndex].convert(this.types[this.argumentIndex], text);
            this.argumentIndex++;
        }
    }

    /**
     * Resets the test method argument index.
     */
    protected void reset() {
        this.argumentIndex = 0;
    }

}
